package com.utils.basejava.concurrent.atguigu;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程操作资源类 判断 干活 通知 防止虚假唤醒
 * 
 * @author XR-8 生产者消费者 Lock版
 */

class ShareData {
	private volatile int product = 0;
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();

	public void produce() throws Exception {
		lock.lock();
		try {
			while (product != 0) {
				condition.await();
			}
			product++;
			System.out.println(Thread.currentThread().getName() + "\t" + "生产一个");
			condition.signal();
		} finally {
			lock.unlock();
		}
	}

	public void consume() throws Exception {
		lock.lock();
		try {
			while (product == 0) {
				condition.await();
			}
			product--;
			System.out.println(Thread.currentThread().getName() + "\t" + "消费一个");
			condition.signal();
		} finally {
			lock.unlock();
		}
	}

}

public class ProductConsumerDemo1 {
	public static void main(String[] args) {
		ShareData sd = new ShareData();
		new Thread(() -> {
			for (int i = 0; i < 5; i++) {
				try {
					sd.produce();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, "pro").start();

		new Thread(() -> {
			for (int i = 0; i < 5; i++) {
				try {
					sd.consume();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, "con").start();
	}
}
